<?php

class Application_Model_AdLink extends Application_Model_DomainObject{
    
    protected $_id;
    
    protected $_title;
    
    protected $_content;

    protected $_target;
    
    protected $_source;
    
    protected $_media;
    
    protected $_campaign;
    
    protected $_name;
    
    protected $_description;

    protected $_code;
    
    const AD_ID_LENGTH = 3;

    /**
     * 根据CODE返回推广链接
     * @param type $code
     * @return Application_Model_AdLink
     */
    public static function getByCode($code){
        return self::getDao()->queryOne(array('code'=>$code));
    }

    /**
     * 返回默认的推广链接
     * @return Application_Model_AdLink
     */
    public static function getDefault(){
        return Application_Model_AdLink::load(0);
    }

    /**
     * 计算推广对应的地址
     * @param type $userid
     */
    public function getTargetUrl($userid){
        $url = sprintf('%1$s?_n=%2$s&_s=%3$s&_m=%4$s&_u=%5$s',  $this->_target, $this->_campaign,  $this->_source,  $this->_media, $userid);
        return $url;
    }
    
    /**
     * 返回推广链接
     * @param type $userid
     * @return string
     */
    public function getAdUrl($userid){
         $sid = $userid . str_pad($this->_id, self::AD_ID_LENGTH,'0',STR_PAD_LEFT);
         $sid = dechex($sid);
         return 'http://www.uuch.com/campaign/ad/sid/'.$sid;
    }
    
    /**
     * 把加密的推广链接还原，返回array('id'=>$shareid,'userid'=>$userid);
     * @param type $sid
     * @return array
     */
    public static function decryptAdUrl($sid){
        $decryptSid = hexdec($sid);
        $shareid = substr($decryptSid, self::AD_ID_LENGTH*-1);
        $userid = substr($decryptSid, 0,  self::AD_ID_LENGTH*-1);
        return array('id'=>$shareid,'userid'=>$userid);
    }
    
    public function getTitle($title){
        //$this->_title='%1$s';
        return sprintf($this->_title,$title);
    }
    public function getMyTitle($title){
        $this->_title = $title;
    }
    public function getContent($content){
        //$this->_content='%1$s';
        return sprintf($this->_content,$content);
    }
    public function getMyContent($content){
        $this->_content = $content;
    }
    
    public static function getByFilter($pagesize, $start) {
        $where = array();
        return self::getDao()->queryPage($where, " id desc ", $pagesize, $start);
    }   
    
    public function getFormatTitle(){
        return $this->_title;
    }
    
    public function getFormatContent(){
        return $this->_content;
    }
}
